package com.yjf.ljr.activity;

import java.util.ArrayList;
import java.util.List;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.dataclass.QueryGiftListDataClass;
import com.yjf.ljr.dataclass.QueryGiftListDataClass.GiftMoneyListInfo;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.ScreenUtils;
import com.yjf.ljr.view.XListView;
import com.yjf.ljr.view.XListView.IXListViewListener;

import cn.sharesdk.framework.i;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class QueryGiftListActivity extends IjActivity implements OnClickListener {
	private int pageNumber = 1;// 分页查询
	private int pageSize = 10;// 分页查询
	@ID("xlvQueryGiftList")
	private XListView mXlxlvQueryGiftList;// 列表
	private CommonAdapter mAdapter;
	private List<GiftMoneyListInfo> mList;
	private static int mSelect; // 选中项
	private static int mSelectbackup; // 选中项
	private String rateOfYear;
	private String giftTradeId;
	@ID("btQueryGiftOk")
	private Button mBtbtQueryGift;// 确定
	private boolean isRefresh = false;
	@ID("tv_title_right")
	private TextView mTvtv_title_right;// 使用规则
	@ID("tvnoteMsgQueryift")
	private TextView mTvtvnoteMsgQueryift;// 提示语
	private String queryGiftPercent;// 提示语

	private PopupWindow popShowUseRule;
	private ImageView mIviviconUseRuleClose;//

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_querygiftlist);
		initControl();
	}

	private void initControl() {
		setTitleStr("加息券");
		setLeftBtnClick();
		mTvtv_title_right.setText("使用规则");
		mTvtv_title_right.setOnClickListener(this);// 使用规则
		mBtbtQueryGift.setVisibility(View.GONE);// 确定
		mBtbtQueryGift.setOnClickListener(this);
		mList = new ArrayList<GiftMoneyListInfo>();
		mAdapter = new CommonAdapter(mContext, mList, R.layout.item_querygif, ViewHolder.class, mHandleCallBack);
		mXlxlvQueryGiftList.setAdapter(mAdapter);
		mXlxlvQueryGiftList.mFooterView.hide();
		mXlxlvQueryGiftList.setPullLoadEnable(true);
		mXlxlvQueryGiftList.setPullRefreshEnable(true);
		mSelect = getIntent().getIntExtra("mSelect", -1);
		queryGiftPercent = getIntent().getStringExtra("queryGiftPercent") + "%";// 提示语
		String noteMsgQueryift = "该项目使用加息券的增益上限是" + "<font color='#ff6600'>" + queryGiftPercent + "</font>" + "，若使用大于"
				+ "<font color='#ff6600'>" + queryGiftPercent + "</font>" + "的加息券，只能获得" + "<font color='#ff6600'>"
				+ queryGiftPercent + "</font>" + "的增益";
		com.yjf.ljr.util.AppUtil.setViewHtml(mTvtvnoteMsgQueryift, noteMsgQueryift);
		mSelectbackup = mSelect;
		mXlxlvQueryGiftList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub

				mSelect = position - 1;
				mSelectbackup = mSelect;
				isRefresh = false;
				mAdapter.notifyDataSetChanged();

			}
		});
		pageNumber = 1;
		showProgressDialog();
		new QueryGiftListTask(pageNumber, pageSize, true).execute();
		mXlxlvQueryGiftList.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				pageNumber = 1;
				isRefresh = true;
				new QueryGiftListTask(pageNumber, pageSize, true).execute();
			}

			@Override
			public void onLoadMore() {
				// TODO Auto-generated method stub
				pageNumber++;
				new QueryGiftListTask(pageNumber, pageSize, false).execute();
			}
		});

	}

	private class QueryGiftListTask extends AsyncTask<Void, Void, String> {
		RequestObject mObject = new RequestObject();
		QueryGiftListDataClass dc = new QueryGiftListDataClass();
		private int pageNumber;
		private int pageSize;
		private boolean isClean;

		public QueryGiftListTask(int pageNumber, int pageSize, boolean isClean) {
			this.pageNumber = pageNumber;
			this.pageSize = pageSize;
			this.isClean = isClean;

		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mObject.method = "queryGiftList";

			mObject.map.put("queryType", "3");// 查询类型 1：红包；2：体验金 3：加息券
			mObject.map.put("tradeType", "ORIGINAL");// 查询类型 ORIGINAL：领取USED：已使用
			// 不传:所有

			mObject.map.put("status", "NORMAL");// status 红包状态 NORMAL：未使用
												// EXPIRE：过期
												// USED: 使用FINISH：已用完

			mObject.map.put("pageNumber", pageNumber);// pageNumber 分页查询
			mObject.map.put("pageSize", pageSize);// pageSize 分页查询

			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dismissProgressDialog();
			if (TextUtils.isEmpty(result)) {
				mSelect = mSelectbackup;
				if (isClean) {
					mList.clear();
				}
				if (dc.giftMoneyList != null && dc.giftMoneyList.size() > 0) {
					mBtbtQueryGift.setVisibility(View.VISIBLE);// 确定
					mList.addAll(dc.giftMoneyList);

				} else {
					mBtbtQueryGift.setVisibility(View.GONE);// 确定
				}

				if (!TextUtils.isEmpty(dc.totalPage + "") && dc.totalPage >= 0) {
					if (mList.size() <= (dc.totalPage - 1) * pageSize) {
						mXlxlvQueryGiftList.mFooterView.show();
					} else {
						mXlxlvQueryGiftList.mFooterView.hide();
					}
				}
				if (dc.giftMoneyList != null && dc.giftMoneyList.size() == 0) {
					mXlxlvQueryGiftList.mFooterView.hide();
				}

				mAdapter.notifyDataSetChanged();
				mXlxlvQueryGiftList.stopLoadMore();
				mXlxlvQueryGiftList.stopRefresh();
			} else {
				showToast(result);
			}
		}
	}

	public static class ViewHolder {
		TextView tvrateOfYear;// "+5%
		TextView tvendDate;// 2015.3.15前可用
		TextView tvuseTypeamount;// 单笔投资满1000元可用
		TextView tvgiftName;// 首次充值送加息券
		LinearLayout llQueryType3;// 条目背景
	}

	private HandleCallBack mHandleCallBack = new HandleCallBack() {

		@Override
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item) {
			// TODO Auto-generated method stub
			ViewHolder viewHolder = (ViewHolder) holder;
			final GiftMoneyListInfo info = (GiftMoneyListInfo) item;
			viewHolder.tvrateOfYear.setText("+" + info.rateOfYear + "%");// "+5%
			if (!TextUtils.isEmpty(info.endDate) && info.endDate.length() > 10) {
				viewHolder.tvendDate.setText(info.endDate.subSequence(0, 10) + "可用");// 2015.3.15前可用
			}

			viewHolder.tvuseTypeamount.setText(info.useType + info.amount + "元可用");// 单笔投资满1000元可用
			viewHolder.tvgiftName.setText(info.giftName);// 首次充值送加息券
			if (mList != null && mList.size() == 1) {
				if (mSelect != -1 && mSelect == position) {// 选中
					if (viewHolder.llQueryType3.getTag() != null && (Boolean) viewHolder.llQueryType3.getTag()
							&& !isRefresh) {// 设置为未选中
						viewHolder.llQueryType3.setTag(false);

						rateOfYear = "";
						giftTradeId = "";
						viewHolder.llQueryType3.setBackgroundResource(R.drawable.shape_item_querygif_btn_bg);
					} else {// 设置为选中
						viewHolder.llQueryType3.setTag(true);
						rateOfYear = info.rateOfYear;
						giftTradeId = info.giftTradeId;
						viewHolder.llQueryType3.setBackgroundResource(R.drawable.shape_btn_item_querygif_bg_pressed);
					}

				} else {
					viewHolder.llQueryType3.setTag(false);
					mSelect = -1;
					// 未选中
					viewHolder.llQueryType3.setBackgroundResource(R.drawable.shape_item_querygif_btn_bg);
				}
			} else {
				if (mSelect != -1 && mSelect == position) {// 选中
					if (viewHolder.llQueryType3.getTag() != null && (Boolean) viewHolder.llQueryType3.getTag()
							&& !isRefresh) {// 设置为未选中
						viewHolder.llQueryType3.setTag(false);
						mSelect = -1;
						rateOfYear = "";
						giftTradeId = "";
						viewHolder.llQueryType3.setBackgroundResource(R.drawable.shape_item_querygif_btn_bg);
					} else {// 设置为选中
						viewHolder.llQueryType3.setTag(true);
						rateOfYear = info.rateOfYear;
						giftTradeId = info.giftTradeId;
						viewHolder.llQueryType3.setBackgroundResource(R.drawable.shape_btn_item_querygif_bg_pressed);
					}

				} else {
					viewHolder.llQueryType3.setTag(false);

					// 未选中
					viewHolder.llQueryType3.setBackgroundResource(R.drawable.shape_item_querygif_btn_bg);
				}
			}

			// convertView.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			// // TODO Auto-generated method stub
			// Intent intent = new Intent();
			// intent.putExtra("rateOfYear", info.rateOfYear);
			// intent.putExtra("giftTradeId", info.giftTradeId);
			// setResult(RESULT_OK, intent);
			// finish();
			// }
			// });
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btQueryGiftOk:

			Intent intent = new Intent();
			intent.putExtra("rateOfYear", rateOfYear);
			intent.putExtra("giftTradeId", giftTradeId);
			intent.putExtra("mSelect", "1");
			intent.putExtra("mSelect", mSelect);
			setResult(RESULT_OK, intent);
			finish();

			break;
		case R.id.tv_title_right:
			if (popShowUseRule != null && popShowUseRule.isShowing()) {
				// 设置背景颜色变暗
				WindowManager.LayoutParams lp = getWindow().getAttributes();
				lp.alpha = 1f;
				getWindow().setAttributes(lp);
				popShowUseRule.dismiss();
				return;
			} else {
				initmPopupWindowView();
				popShowUseRule.showAtLocation(v, Gravity.CENTER, 0, 0);
			}
			break;
		case R.id.iviconUseRuleClose:
			if (popShowUseRule != null && popShowUseRule.isShowing()) {

				WindowManager.LayoutParams lp = getWindow().getAttributes();
				lp.alpha = 1f;
				getWindow().setAttributes(lp);

				popShowUseRule.dismiss();
				popShowUseRule = null;
			}
			break;
		default:
			break;
		}
	}

	public void initmPopupWindowView() {

		// // 获取自定义布局文件pop.xml的视图
		View customView = getLayoutInflater().inflate(R.layout.popshowuserule_item, null, false);
		TextView tvpopshowuserrule = (TextView) customView.findViewById(R.id.tvpopshowuserrule);
		ImageView mIviviconUseRuleClose = (ImageView) customView.findViewById(R.id.iviconUseRuleClose);
		mIviviconUseRuleClose.setOnClickListener(this);
		// LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
		// tvpopshowuserrule.getLayoutParams();
		// params.width = (int) ScreenUtils.getScreenWidth(mContext) - 200;
		// params.height = (int) ScreenUtils.getScreenHeight(mContext) / 3;
		// params.gravity = Gravity.CENTER;
		// tvpopshowuserrule.setLayoutParams(params);
		popShowUseRule = new PopupWindow(customView, (int) ScreenUtils.getScreenWidth(mContext),
				(int) ScreenUtils.getScreenHeight(mContext));
		popShowUseRule.setOutsideTouchable(false);
		popShowUseRule.setFocusable(false);
		popShowUseRule.setBackgroundDrawable(new BitmapDrawable());
		// 设置背景颜色变暗
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = 0.5f;
		getWindow().setAttributes(lp);
		// // 自定义view添加触摸事件
		// customView.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// if (popShowUseRule != null && popShowUseRule.isShowing()) {
		//
		// WindowManager.LayoutParams lp = getWindow().getAttributes();
		// lp.alpha = 1f;
		// getWindow().setAttributes(lp);
		//
		// popShowUseRule.dismiss();
		// popShowUseRule = null;
		// }
		//
		// return false;
		// }
		// });

	}
}
